/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.cn.xiaonuo.tcrfinance.sysmgmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.SystemConstant;
import com.cn.xiaonuo.core.exception.ServiceException;
import com.cn.xiaonuo.core.factory.PageFactory;
import com.cn.xiaonuo.core.pojo.page.PageResult;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.enums.SystemEnum;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserHpcMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.param.SysUserHpcParam;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.SysRoleHpcService;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.SysUserRoleHpcService;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.SysUserHpcService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class SysUserHpcServiceImpl extends ServiceImpl<SysUserHpcMapper, SysUserHpcEntity> implements SysUserHpcService {
	@Autowired
	private SysUserRoleHpcService sysUserRoleService;
	@Autowired
	private SysRoleHpcService sysRoleService;

	@Autowired
	private SysUserHpcMapper sysUserHpcMapper;

	@Override
	public PageResult<SysUserHpcEntity> queryPage(SysUserHpcParam sysUserHpcParam) {
		QueryWrapper<SysUserHpcEntity> queryWrapper = new QueryWrapper<>();
		if (ObjectUtil.isNotNull(sysUserHpcParam)) {
			// 根据元素文本 模糊查询
			if (ObjectUtil.isNotEmpty(sysUserHpcParam.getUsername())) {
				queryWrapper.lambda().like(SysUserHpcEntity::getUsername, sysUserHpcParam.getUsername());
			}
			// 根据商品唯一标识符 模糊查询
			if (ObjectUtil.isNotEmpty(sysUserHpcParam.getCreateUserId())) {
				queryWrapper.lambda().like(SysUserHpcEntity::getCreateUserId, sysUserHpcParam.getCreateUserId());
			}
		}
	/*	IPage<SysUserHpcEntity> page = this.page(
			new Query<SysUserHpcEntity>().getPage(params),
			new QueryWrapper<SysUserHpcEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
				.eq(createUserId != null,"create_user_id", createUserId)
		);*/
		return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserHpcEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void saveUser(SysUserHpcParam sysUserParam) {
		SysUserHpcEntity user=new SysUserHpcEntity();
		BeanUtil.copyProperties(sysUserParam,user);
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(SysUserHpcParam sysUserParam) {
		SysUserHpcEntity user=new SysUserHpcEntity();
		BeanUtil.copyProperties(sysUserParam,user);
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserHpcEntity userEntity = new SysUserHpcEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserHpcEntity>().eq("user_id", userId).eq("password", password));
	}

	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserHpcEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == SystemConstant.SUPER_ADMIN){
			return ;
		}

		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new ServiceException(SystemEnum.VALIDATE_ROLE_CREATE);
		}
	}
	/**
	 * 根据id，查询系统用户
	 */
	@Override
	public SysUserHpcEntity queryById(Long id){
	/*	QueryWrapper<SysUserHpcEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserHpcEntity::getUserId,id);
		sysUserHpcMapper.selectOne(queryWrapper)*/
		return this.getById(id);
	}
}
